package org.de.maeyer.statistic;

import java.util.Comparator;


/**
 * @author Peter De Maeyer
 */
public class ExtremaAccumulator implements Accumulator {
	
	private final Comparator comparator;
	
	protected Object minimum;

	protected Object maximum;
	
	public ExtremaAccumulator(Comparator comparator) {
		this(comparator, null, null);
	}

	public ExtremaAccumulator(Comparator comparator, Object minimum, Object maximum) {
		this.comparator = comparator;
		this.minimum = minimum;
		this.maximum = maximum;
	}
	
	@Override
	public void accumulate() {
	    throw new UnsupportedOperationException();
	}
	
	@Override
	public void accumulateDouble(double value) {
	    accumulateObject(value);
	}
	
	@Override
	public void accumulateLong(long value) {
	    accumulateObject(value);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void accumulateObject(Object value) {
		if ((minimum == null) || comparator.compare(minimum, value) > 0) {
			minimum = value;
		}
		if ((maximum == null) || comparator.compare(maximum, value) < 0) {
			maximum = value;
		}
	}
	
	@Override
	public void appendTo(StatisticsBuilder builder) {
	    builder.setExtrema(minimum, maximum);
	}

	public void reset() {
		minimum = null;
		maximum = null;
	}
}